/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedLineData } from '@amcax/base';
import { canCurvesFormClosedLoop } from '@app-base/common/utils/lines-coplanar';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type Params = {
  mode: 'parallel';
  curves: string[];
};

/**
 * 填充曲面命令
 *
 * - 选中一条或多条曲线，创建一个填充曲面
 * - 若弹窗包含一个及以上的输入对象，则应保证完成键可点击。
 *  即 前端做个初步的判断，但是不禁止用户去后台做更精确的判断
 */
function CmdFillSurface({ title, onClose, props }: CurvedCmdDialogParams) {
  const [curves, setCurves] = useState<pickedLineData[]>([]);

  const schema: RJSFSchema = {
    type: 'array',
    items: {
      type: 'string',
      enum: [],
    },
    format: PickInputRJSFFormat.MultiPickSketchCurve,
    uniqueItems: true,
  };

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [curves]);

  useAsyncEffect(async () => {
    if (props == null) {
      setCurves([]);
      return;
    }

    const params: Params = props.params;
    const { curves } = params;

    await initEditDependency(curves);

    setCurves(
      curves.map(
        (curve) => picker.generatePickObjByPickID(curve) as pickedLineData,
      ),
    );
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) return;

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-fill-surface', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        type: 'Fill',
        a: {
          curves: curves.map((c) => c.edgeId),
          method: 'parallel',
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    return curves.length >= 1;
  };

  const preview = async () => {
    clear();

    if (!isFormDataValid()) return;

    const points = curves.map((c) => c.edgeData);
    if (!canCurvesFormClosedLoop(points, 1e-3)) {
      // 仅曲线可以组成闭合环时，执行预览
      return;
    }

    await execute(true);
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      onChange={(v) => {
        setCurves(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        'ui:placeholder': '请输入边界曲线',
        'ui:autofocus': true,
      }}
      formData={curves}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdFillSurface: CurvedBaseCommand = {
  id: 'CmdFill',
  label: 'command.fill-surface',
  icon: 'commands/curved/fill',
  help: {
    remark: 'tips.redo',
  },
  create: (label, onClose, props) => (
    <CmdFillSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
